package com.hhly.rabbitmq.publish_subscribe;

import java.io.IOException;

import com.hhly.rabbitmq.RabbitMQUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class ReceiveLogs {
	public static void main(String[] args) throws Exception {
		receive("1","1");
		receive("2","2");
	}
	public static void receive(final String name,final String num) throws Exception {
		Channel channel = RabbitMQUtil.getChannel();
		//声明名为“logs”的exchange的，方式为"fanout" (广播)
		//channel.exchangeDeclare(EmitLog.EXCHANGE_NAME, "fanout");
		//该语句得到一个随机名称的Queue，该queue的类型为non-durable（不持久）、exclusive（独有）、auto-delete（自动删除）的，将该queue绑定到上面的exchange上接收消息。
		//String queueName = channel.queueDeclare().getQueue();
		String queueName = "logs"+name;
		channel.queueDeclare(queueName, true, false, false, null);
		//第三个参数为空表示所有消息都接收，在exchange type为“fanout”方式下该值被忽略！
		channel.queueBind(queueName, EmitLog.EXCHANGE_NAME, "");
		System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				String message = new String(body, "UTF-8");
				System.out.println(name +"-"+ num + " [x] Received '" + message + "'");
			}
		};
		channel.basicConsume(queueName, true, consumer);
	}

}
